package com.biz.utils;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;


/**
 * String工具类
 * 
 * @author 刘佳佳
 * 
 */
public class StringUtil {

	/**
	 * 格式化字符串
	 * 
	 * 例：formateString("xxx{0}bbb",1) = xxx1bbb
	 * 
	 * @param str
	 * @param params
	 * @return
	 */
	public static String formateString(String str, String... params) {
		for (int i = 0; i < params.length; i++) {
			str = str.replace("{" + i + "}", params[i] == null ? "" : params[i]);
		}
		return str;
	}
	/**
	 * 判断是否为空
	 * @param obj
	 * @return
	 */
	public static boolean isNullOrEmpty(Object obj) {	
		return obj == null || "".equals(obj.toString()) || "null".equals(obj.toString());
	}
	
	public static String toString(Object obj){
		if(obj == null) return "null";
		return obj.toString();
	}
	/**
	 * 把字符串 和集合内容拼接
	 * @param s
	 * @param delimiter
	 * @return
	 */
	public static String join(Collection s, String delimiter) {
        StringBuffer buffer = new StringBuffer();
        Iterator iter = s.iterator();
        while (iter.hasNext()) {
            buffer.append(iter.next());
            if (iter.hasNext()) {
                buffer.append(delimiter);
            }
        }
        return buffer.toString();
    }
	
	/**
	 * 将逗号分割的字符串 重新拼接 加入单引号  使得查询条件可用
	 * @param arg
	 * @return
	 */
	public static String formatSqlIn(String arg){
    	StringBuilder sb=new StringBuilder();
    	if(!StringUtil.isNullOrEmpty(arg)){
        	String[] temp=arg.split(",");
        	for(int i=0;i<temp.length;i++){
        		
        		if(i!=(temp.length-1)){
        			sb.append("'").append(temp[i].trim()).append("'").append(",");
        		}else{
        			sb.append("'").append(temp[i].trim()).append("'");
        		}
        	}
        	
    	}
    	
    	return sb.toString();
    }
	
	
	public static String getStringFromMap(Map<String, Object> map, String key, String defaultValue) {
        if (key == "" || key == null) {
            return defaultValue;
        }
        String result = (String) map.get(key);
        if (result == null) {
            return defaultValue;
        } else {
            return result;
        }
    }
	
	 public static int getIntFromMap(Map<String, Object> map, String key) {
	        if (key == "" || key == null) {
	            return 0;
	        }
	        if (map.get(key) == null) {
	            return 0;
	        }
	        return Integer.parseInt((String) map.get(key));
	    }
	 
	  public static InputStream getStringStream(String sInputString) {
	        ByteArrayInputStream tInputStringStream = null;
	        if (sInputString != null && !sInputString.trim().equals("")) {
	            tInputStringStream = new ByteArrayInputStream(sInputString.getBytes());
	        }
	        return tInputStringStream;
	    }

}
